let express=require(`express`)
let router=express.Router()
let multer=require(`multer`)
let upload=multer({dest:'uploads/'})
let db=require(`../util/db`)
let moment=require(`moment`)
let pub_date=moment().format('YYYY-MM-DD HH:MM:SS')
// 新增文章
router.post(`/my/article/add`,upload.single('cover_img'),(req,res)=>{
    let {title,cate_id,content,state}=req.body
    let cover_img=req.file.originalname
    let {id}=req.user
    // console.log(author_id)
    // console.log(title,cate_id,content,state,cover_img)
    // console.log(444)
db(`insert into article set title='${title}',cate_id='${cate_id}',content='${content}',state='${state}',
cover_img='${cover_img}',author_id='${id}',pub_date='${pub_date}',is_delete='0'`,(err,result)=>{
    if(err||result.affectedRows===0) return res.send({code:1,msg:'sorry'})
    res.send({code:0,msg:'新增成功'})
})
})
// 获取文章列表数据
router.get(`/my/article/list`,(req,res)=>{
    let {pagenum,pagesize,cate_id,state}=req.query
    pagenum=pagenum*pagesize-pagenum
    if(!state) state='.'
    if(!cate_id) cate_id='.'
    // console.log(state,cate_id)
    db(`select * from article where state REGEXP'${state}' and cate_id REGEXP'${cate_id}' and is_delete=0 LIMIT ${pagenum},${pagesize}`,(err,result)=>{
        // console.log(err)
        // console.log(result)
        if(err||result.length===0) return res.send({code:1,msg:'sorry1',err})
        db(`SELECT COUNT(*)aa FROM article where state REGEXP'${state}' and cate_id REGEXP '${cate_id}' and is_delete=0`,(err1,result1)=>{
            console.log(result1)
            if(err1) return res.send({code:1,msg:'sorry'})
            res.send({code:0,msg:'获取成功',data:result,total:result1[0].aa})
        })
    })
})

// 根据id删除数据
router.get(`/my/article/delete/:id`,(req,res)=>{
    let {id}=req.params
    // console.log(id)
    db(`update article set is_delete=1 where id=${id}`,(err,result)=>{
        // console.log(err)
        // console.log(result)
        if(err||result.changedRows===0) return res.send({code:1,msg:'sorry'})
        res.send({code:0,msg:'删除成功'})
    })
})
// 根据id获取文章详情
router.get(`/my/article/:id`,(req,res)=>{
let {id}=req.params
db(`select * from article where id=${id} and is_delete=0`,(err,result)=>{
    console.log(err)
    console.log(result)
    if(err||result.length===0) return res.send({code:1,msg:'sorry'})
    res.send({code:0,msg:'获取成功',data:result[0]})
})
})
// 根据id更新文章信息
router.post(`/my/article/edit`,upload.single(`cover_img`),(req,res)=>{
    let {id,title,cate_id,content,state}=req.body
    let cover_img=req.file.originalname
    db(`update article set title='${title}',cate_id='${cate_id}',content='${content}',state='${state}',cover_img='${cover_img}' where id=${id} and is_delete=0`,(err,result)=>{
        // console.log(err)
        // console.log(result)
        if(err||result.changedRows===0) return res.send({code:1,msg:'sorry'})
        res.send({code:0,msg:'更新成功'})
    })
})
module.exports=router